package cmd

import (
	"errors"
	"fmt"
	"strings"

	"math-clc/enum"
	"math-clc/tool"

	"github.com/spf13/cobra"
)

var (
	dividedByZeroHanding int // 除 0 如何处理
)

var divideCmd = &cobra.Command{
	Use:   "divide",
	Short: "Divide subcommand divide all passed args.",
	Args:  cobra.MinimumNArgs(2), // 校验参数，至少需要两个参数
	Run: func(cmd *cobra.Command, args []string) {

		values := tool.ConvertArgsToFloat64Slice(args, enum.ErrorHandling(parseHandling))
		result := values[1]
		for i := 1; i < len(values); i++ {
			if values[i] == 0 {
				switch enum.ErrorHandling(dividedByZeroHanding) {
				case enum.ReturnOnDividedByZero:
					break
				case enum.PanicOnDividedByZero:
					panic(errors.New("divided by 0"))
				}
			}
			result /= values[i]
		}

		fmt.Printf("%s = %.2f\n", strings.Join(args, "/"), result)
	},
}

func init() {
	divideCmd.Flags().IntVarP(&dividedByZeroHanding, "divide_by_zero", "d", int(enum.PanicOnDividedByZero), "do what when divided by zero")

	rootCmd.AddCommand(divideCmd)
}
